var express = require("express");  // 服务器搭建
var crypto = require("crypto");  // AES-256-CBC token解密
var path = require("path");
var request = require("request");
var cookieParser = require("cookie-parser");
var app = express();
var access_token_code = null;

var calluri = "http://f.yiban.cn/iapp669687";
var appId = "535160b8bf33c092";
var appSecret = "7873e89fa30650413a416261b3ebf730";

// 搭建一个静态资源服务器
app.use(express.static(path.resolve(__dirname, "public")));

app.use(cookieParser("ynau"));

const allowCors = function (req, res, next) {
  //设置允许跨域的域名，*代表允许任意域名跨域
  res.header("Access-Control-Allow-Origin", req.headers.origin);
  // //允许的header类型
  res.header("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Requested-With");
  // //跨域允许的请求方式 
  res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
  // 可以带cookies
  res.header("Access-Control-Allow-Credentials", true);
  if (req.method == 'OPTIONS') {
    res.sendStatus(200);
  } else {
    next();
  }
}

app.use(allowCors)

app.use(express.urlencoded({ extended: true }));
app.use(express.json());

app.use('/upload', require('./router/upload'));
app.use('/report', require('./router/report'));
app.use('/isdao', require('./router/isdao'));

// 解密方法
const decrypt = (crypted, key, iv) => {
  let decoded = null;
  try {
    var decipher = crypto.createDecipheriv('aes-256-cbc', key, iv);
    decipher.setAutoPadding(false);
    decoded = decipher.update(crypted, 'hex', 'utf8');
    decoded += decipher.final('utf8');
  } catch (error) {
    console.error(error);
  }
  return decoded;
};

app.post('/userInfo', function (req, res) {
  const token = req.body.token;
  var url = 'https://openapi.yiban.cn/user/verify_me?access_token=' + String(token);
  request(url, function (err, response, body) {
    if (!err && response.statusCode == 200) {
      res.send(body);
    } else {
      res.send('请求失败');
    }
  })
})

app.get('/login', async function (req, res) {
  res.status(302);
  res.header("Location", "https://oauth.yiban.cn/code/html?client_id=" + appId + "&redirect_uri=" + calluri);
  res.send(null);
})

app.post('/verify', async function (req, res) {
  if (req.body.verify_request) {
    access_token_code = req.body.verify_request;
    var user_code = await decrypt(access_token_code, appSecret, appId);
    var reg = /(?<=access_token":").+(?=",)/;
    if(user_code.match(reg)){
      var access_token = user_code.match(reg)[0];
      console.log(access_token);
      res.status(200);
      res.send({
        code: 0,
        userMsg: '请求成功',
        data: {
          access_token,
          yb_uid: req.body.yb_uid
        }
      });
    }else{
      res.status(302);
      res.header("Location", "https://oauth.yiban.cn/code/html?client_id=" + appId + "&redirect_uri=" + calluri);
      res.send(null);
    }
  }
})

app.listen(9527, function () {
    console.log("server listening on 9527");
});